<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="depts" :default-expand-all="true" :expand-on-click-node="false" :props="defaultProps">
        <template v-slot="{ data }">
          <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <!-- $event 实参 表示类型 -->
              <el-dropdown @command="hCommand($event,data)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 弹框 -->
    <add-depts ref="addDepts" :visible.sync="isShow" :current="currentId" :title="title" @refresh="getDepartment" />
  </div>
</template>
<script>
import { getDepartment, delDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import addDepts from './components/addDepts.vue'
export default {
  name: 'Department',
  components: { addDepts },
  data() {
    return {
      depts: [{
        name: '传智教育',
        children: [
          { name: '总裁办' },
          { name: '行政部' },
          { name: '财务部' }
        ]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      isShow: false,
      currentId: null,
      title: '新增部门'

    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartment()
      const newDepts = transListToTreeData(res.data, 0)
      this.depts = newDepts
    },
    async hCommand(type, data) {
      if (type === 'add') {
        this.isShow = true
        this.title = '新增部门'
        this.currentId = data.id
      }

      if (type === 'edit') {
        this.isShow = true
        this.title = '修改部门'
        this.currentId = data.id
        this.$nextTick(() => {
          this.$refs.addDepts.getDepartmentDetails()
        })
      }

      if (type === 'del') {
        this.$confirm('你确定要删除吗?').then(async() => {
          const res = await delDepartment(data.id)
          this.$message.success(res.message)
          this.getDepartment()
        }).catch(() => {})
      }
    }

  }
}
</script>
<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
